<?php
/**
 * @user:andy
 * @date:2021/6/14
 * @company:http://www.sjdphp.com
 * @desc:
 */

namespace app\admin\controller;


use app\common\controller\BackBaseController;
use app\admin\validate\BackValidate;
use app\common\server\Json;
use app\common\server\SystemLog;
use app\common\model\Back as BackModel;
use app\common\model\BackLog as BackLogModel;
use app\common\server\Tools;
use think\facade\Cookie;

class Login extends BackBaseController
{
    protected function initialize(){}

    public function signIn(){
        if($this->request->isPost()){
            ## 接受参数
            $param['username'] = $this->request->param("username",'','trim');
            $param['password'] = $this->request->param("password",'','trim');
            $param['captcha']  = $this->request->param("captcha",'','trim');

            ## 校验参数
            $validate = new BackValidate();
            if(!$validate->scene("sign_in")->check($param)) return Json::error($validate->getError());

            ## 根据用户名查询管理员数据
            try{
                $backInfo = BackModel::where(array('username' => $param["username"],'back_status' => config("project.mysql_code.table_normal")))->find();
            }catch(\Exception $e){
                SystemLog::insertLog($e->getMessage());
                return Json::error('系统错误,请稍后重试');
            }

            ## 校验数据是否存在
            if(empty($backInfo)){
                return Json::error('账号不存在或已停用');
            }

            ## 校验密码是否合法
            if(!Tools::comparePassword($param["password"],$backInfo["back_key"],$backInfo["password"])) return Json::error("账号或密码错误,请重新输入");

            ## 订阅事件
            event("BackSignIn",$backInfo);

            return Json::success('登陆成功');
        }else{
            return view();
        }
    }

    public function signOut(){
        if($this->request->isGet()){

            event("BackSignOut");

            return Json::success("退出成功");

        }else{
            return Json::error('请求方式错误');
        }
    }


}